﻿using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System;

public class JSONHelper
{
    /// <summary>
    /// Serializes a data contract into a JSON format, this works with any type by using generics
    /// </summary>
    /// <typeparam name="T">The object type to be serialized</typeparam>
    /// <param name="obj">The object be to serialized</param>
    /// <returns></returns>
    public static string Serialize<T>(T obj)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        string retVal = Encoding.Default.GetString(ms.ToArray());
        ms.Dispose();
        return retVal;
    }

    /// <summary>
    /// Unserializes a data contract from a string in JSON format. It will return the right data type.
    /// </summary>
    /// <typeparam name="T">The object type to be serialized</typeparam>
    /// <param name="json">String in JSON format</param>
    /// <returns>The unserialized object</returns>
    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        ms.Dispose();
        return obj;
    }
}
